{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# ONNX 模型文件转换为 Python脚本\n",
    "\n",
    "[onnx2script](https://github.com/microsoft/onnxscript/blob/main/tools/onnx2script.py) 模块提供一个脚本，用于使用 `onnxscript` 库将 ONNX 模型文件转换为 Python 脚本。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "import onnx\n",
    "import onnxscript\n",
    "\n",
    "def convert2script(\n",
    "    input_file_name: str, output_file_name: str|None=None, verbose: bool=True,\n",
    "    load_external_data=False,\n",
    ") -> None:\n",
    "    \"\"\"使用 `onnxscript` 库将 ONNX 模型文件转换为 Python 脚本\"\"\"\n",
    "    model = onnx.load(input_file_name, load_external_data=load_external_data)\n",
    "    python_code = onnxscript.proto2python(\n",
    "        model, use_operators=not verbose, inline_const=not verbose\n",
    "    )\n",
    "\n",
    "    # If output file name is not provided, use the input file name with .py extension\n",
    "    if output_file_name is None:\n",
    "        base_name = os.path.splitext(input_file_name)[0]  # Remove extension\n",
    "        output_file_name = base_name + \".py\"\n",
    "\n",
    "    with open(output_file_name, \"w\", encoding=\"utf-8\") as f:\n",
    "        f.write(python_code)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "input_file_name = \"/media/pc/data/board/arria10/lxw/tasks/tools/npuusertools/models/test/ai_isp/mirnet_newest_RGB_SE_conv33_k1.0_opt.onnx\"\n",
    "convert2script(input_file_name)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "ai",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.2"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
